<template>
    <div class="hotspot-container">
        <div class="header">
            <n-row>
                <n-col :span="12">
                    <n-statistic label="统计文章">
                        <template #suffix>
                            <n-number-animation ref="numberAnimationInstRef" :from="0" :to="resultData.length" />
                            条
                        </template>
                    </n-statistic>
                </n-col>
                <n-col :span="12">
                    <n-statistic label="在线人数">
                        <n-number-animation ref="numberAnimationInstRef" :from="0" :to="counts" />
                    </n-statistic>
                </n-col>
            </n-row>
        </div>

        <div class="notelist  mt-30 mb-40">
            <n-config-provider :theme="theme">
                <n-space vertical :size="12">
                    <n-data-table :max-height="450" :loading="noteDataLoading" :bordered="false" :single-line="false"
                        :columns="columns" :data="resultData" :pagination="pagination">
                    </n-data-table>
                </n-space>
            </n-config-provider>
        </div>

        <div class="notelist  mt-30 mb-40">
            <n-config-provider :theme="theme">
                <n-space vertical :size="12">
                    <n-data-table :scroll-x="500" :max-height="250" virtual-scroll default-expand-all
                        :loading="taskDataLoading" :bordered="false" :single-line="false" :columns="taskColumns()"
                        :data="resultTaskData" :pagination="pagination">
                    </n-data-table>
                </n-space>
            </n-config-provider>

        </div>
        <n-config-provider :theme="theme">
            <n-drawer @after-leave="closeDrawer" v-model:show="active" :width="400" height="55%" :placement="placement">
                <n-drawer-content title="创建定时任务">
                    <n-form ref="formRef" :label-width="80" label-placement="left" :model="cornTask" :rules="rules"
                        :size="size">
                        <n-form-item label="文章标题">
                            <n-input disabled v-model:value="cornTask.taskName" placeholder="输入姓名" />
                        </n-form-item>
                        <n-form-item label="接收邮箱" path="email">
                            <!-- <n-input v-model:value="cornTask.email" placeholder="输入年龄" /> -->
                            <n-select placeholder="选择邮箱" filterable v-model:value="cornTask.email"
                                :options="timeOptions" clearable />
                        </n-form-item>
                        <n-form-item label="发送时间" path="sendTime">
                            <!-- <n-input v-model:value="cornTask.sendTime" placeholder="时间" /> -->
                            <n-date-picker style="width: 100%;" v-model:value="cornTask.sendTime" type="datetime"
                                clearable />
                        </n-form-item>
                        <n-form-item label="备注">
                            <n-input v-model:value="cornTask.remarks" placeholder="备注" />
                        </n-form-item>
                        <n-form-item label="发送者">
                            <n-input disabled v-model:value="cornTask.taskUserName" placeholder="输入姓名" />
                        </n-form-item>
                        <n-form-item>
                            <n-button style="width: 100%;" attr-type="button" @click="handleCreateTask">
                                创建
                            </n-button>
                        </n-form-item>
                    </n-form>
                </n-drawer-content>
            </n-drawer>
        </n-config-provider>
    </div>




</template>

<script setup lang="ts">

import { h } from 'vue'
import { NButton, useMessage, useDialog, NSwitch, NFlex, NTime, NTag, NText, NCountdown } from 'naive-ui'
import type { DataTableColumns } from 'naive-ui'
import { getNoteFormList, noteDelete, setIsPublic, obtainEmails, createTask, taskList, deleteTask, startUserTask, removeUserTask } from '@/apis/index';
import { getImageFileName } from '@/utils/index';
import { useMain } from '@/store/index';
import { darkTheme, GlobalTheme, DrawerPlacement, FormInst } from 'naive-ui';
import { useDark } from '@vueuse/core';
const isDark = useDark()
interface Task {
    id?: number;
    key?: string;
    taskName: string;
    taskUserName: string;
    noteId: string;
    sendTime: any,
    createTime: Date,
    email: string;
    taskState: string;
    remarks: string;

}
const store = useMain();
const theme = ref<GlobalTheme | null>(isDark.value ? darkTheme : null);
const formRef = ref<FormInst | null>(null);
const size = ref<'small' | 'medium' | 'large'>('medium')
const active = ref(false);
const counts = computed(() => store.obtainOnline);
const dialog = useDialog()
const placement = ref<DrawerPlacement>('top')
const message = useMessage();
const timeOptions = ref<any>([]);
const currenName = localStorage.getItem('u');
const resultData: any = ref([]);
const resultTaskData = ref<Task[]>([]); // 定时任务
const loadingBar = useLoadingBar();
const noteDataLoading = ref(false);
const taskDataLoading = ref(false);
const userOptions = ref<any[]>([]);
const cornTask = ref<Partial<Task>>({
    taskName: '',
    taskUserName: '',
    noteId: '',
    createTime: new Date(),
    sendTime: new Date().getTime(),
    email: '',
    remarks: '',
    taskState: 'off',
});
const pagination = {
    pageSize: 10
}
const rules: any = {
    email: {
        required: true,
        message: '输入邮箱',
        trigger: ['input']
    },
    sendTime: {
        type: 'number',
        required: true,
        trigger: ['blur', 'change'],
        message: '输入时间',
    }
}

function handleCreateTask(e: MouseEvent) {
    e.preventDefault()
    formRef.value?.validate((errors) => {
        if (!errors) {
            loadingBar.start();
            cornTask.value.sendTime = new Date(cornTask.value.sendTime);
            cornTask.value.taskUserName = cornTask.value.taskUserName ?? localStorage.getItem('u') as string;
            createTask(cornTask.value).then(res => {
                if (res.status === 200) {
                    message.success(res.message)
                }
                cornTask.value = {
                    taskName: '',
                    taskUserName: '',
                    noteId: '',
                    createTime: new Date(),
                    sendTime: null,
                    email: '',
                    taskState: 'off',
                };
                loadingBar.finish();
            })
            // cornTask.value.sendTime
            active.value = false;
            init();
        } else {
            console.log(errors)
            message.error('不可为空')
        }
    })
}

const createColumns = (): DataTableColumns<any> => {
    return [
        {
            title: '标题',
            ellipsis: {
                tooltip: true
            },
            key: 'title'
        },
        {
            title: '用户名',
            key: 'noteUsername'
        },
        {
            title: '是否公开',
            key: 'userId',
            render(row) {
                return h(NSwitch, {
                    value: row.isPublic === 0 ? true : false,
                    disabled: localStorage.getItem('u') === 'Leon' ? false : true,
                    onUpdateValue(val) {
                        row.isPublic = val ? 0 : 1;
                        setIsPublic({ noteId: row.id, isPublic: row.isPublic }).then(res => {
                            if (res.status === 200) {
                                message.success(res.message)
                            }
                        })
                    }
                })
            }
        },
        {
            title: 'Action',
            key: 'actions',
            align: 'center',
            render(row) {
                return h(NFlex, {
                    justify: 'center',
                    align: 'center'
                }, {
                    default: () => [
                        h(
                            NButton,
                            {
                                type: 'warning',
                                size: 'small',
                                disabled: checkCronTime(row),  // 建造者全可以改
                                onClick: async () => {
                                    active.value = true;
                                    const emails = await obtainEmails({ username: localStorage.getItem('u') });
                                    let arr = emails.data;
                                    userOptions.value = emails.data;
                                    timeOptions.value = arr.map(item => {
                                        return {
                                            label: item.email,
                                            value: item.email
                                        }
                                    });
                                    cornTask.value.taskName = row.title
                                    cornTask.value.noteId = row.id;
                                    cornTask.value.taskState = 'off';
                                    cornTask.value.taskUserName = localStorage.getItem('u') as string;
                                }
                            },
                            { default: () => '定时' }
                        ),
                        h(
                            NButton,
                            {
                                type: 'primary',
                                size: 'small',
                                disabled: localStorage.getItem('u') === 'Leon' ? false : true,
                                onClick: () => {
                                    dialog.warning({
                                        title: '警告',
                                        content: '你确定？删除',
                                        positiveText: '确定',
                                        negativeText: '不确定',
                                        onPositiveClick: () => {
                                            if (row.disabled) {
                                                message.warning('定时任务在进行中，不可删除')
                                                return;
                                            }
                                            noteDelete({ noteId: row.id, imageUrl: getImageFileName(row.imageUrl) ? getImageFileName(row.imageUrl) : '' }).then(res => {
                                                if (res.status === 200) {
                                                    message.success('删除成功')
                                                    getNoteFormList({ search: '' }).then(res => {
                                                        if (res.status === 200) {
                                                            resultData.value = res.data;

                                                        }
                                                    })
                                                }
                                            })
                                        },
                                    })
                                }
                            },
                            { default: () => '删除' }
                        )

                    ]
                }

                )
            }
        }
    ]
}


const taskColumns = (): DataTableColumns<Task> => {
    return [
        {
            type: 'expand',
            renderExpand: (row) => {
                return h(NFlex, {
                    align: 'center'
                }, {
                    default: () => [
                        h(NText, { depth: 3 }, { default: () => `邮箱：${row.email} 创建时间：` }),
                        h(NText, { depth: 3 }, {
                            default: () => h(NTime, {
                                time: new Date(row.createTime),
                                type: 'datetime',
                                format: 'yyyy-MM-dd HH:mm:ss'
                            })
                        }),
                        h(NText, { depth: 3 }, { default: () => `备注：${row.remarks}` }),
                    ]
                })

            }
        },
        {
            title: '任务标题名称',
            ellipsis: {
                tooltip: true
            },
            key: 'taskName',
            fixed: 'left',
            render(row) {
                return h('span', {
                    class: 'name',
                }, { default: () => row.taskName })
            }
        },
        {
            title: '接收人',
            key: 'taskUserName',
            align: 'center',
            fixed: 'left',
            ellipsis: {
                tooltip: true
            },
        },
        {
            title: '状态',
            key: 'taskState',
            align: 'center',
            fixed: 'left',
            render(row) {

                if (row.taskState === 'off') {
                    return h(
                        NTag,
                        {
                            style: {
                                marginRight: '6px'
                            },
                            type: 'warning',
                            bordered: false
                        },
                        {
                            default: () => '待发送'
                        }
                    )
                } else if (row.taskState === 'success') {
                    return h(
                        NTag,
                        {
                            style: {
                                marginRight: '6px'
                            },
                            type: 'success',
                            bordered: false
                        },
                        {
                            default: () => '已发送'
                        }
                    )
                } else if (row.taskState === 'loading') {
                    return h(
                        NTag,
                        {
                            style: {
                                marginRight: '6px'
                            },
                            type: 'info',
                            bordered: false
                        },
                        {
                            default: () => '发送中'
                        }
                    )
                } else {
                    return h(
                        NTag,
                        {
                            style: {
                                marginRight: '6px'
                            },
                            type: 'error',
                            bordered: false
                        },
                        {
                            default: () => '已关闭'
                        }
                    )
                }
            }
        },
        // {
        //     title: '接收邮箱',
        //     key: 'email',
        //     align: 'center'
        // },
        // {
        //     title: '备注',
        //     key: 'remarks'
        // },
        {
            title: '发送时间',
            key: 'sendTime',
            align: 'center',
            fixed: 'right',
            ellipsis: {
                tooltip: true
            },
            render(row) {
                if (row.taskState === 'off') {
                    // 未启用显示
                    return h(NTime, {
                        time: new Date(row.sendTime),
                        type: 'datetime',
                        format: 'yyyy-MM-dd HH:mm:ss'
                    })
                }
                // 用送时间求减去当前时间求剩余时间 
                let time = new Date(row.sendTime).getTime() - new Date().getTime();
                if (time > 0 && row.taskState === 'loading') {
                    return h(
                        NTag,
                        {
                            style: {
                                marginRight: '6px'
                            },
                            type: 'info',
                            bordered: false
                        },
                        {
                            default: () => h(NCountdown, {
                                duration: time,
                                onFinish: () => {
                                    init();
                                }
                            })
                        })
                } else {
                    return h(
                        NTag,
                        {
                            style: {
                                marginRight: '6px'
                            },
                            type: 'error',
                            bordered: false
                        },
                        {
                            default: () => '已过期'
                        }
                    )
                }



            }
        },
        {
            title: '操作',
            key: 'actions',
            align: 'center',
            fixed: 'right',
            render(row) {
                if (row.taskState === 'off') {
                    return h(NFlex, {
                        justify: 'center',
                        align: 'center'
                    }, {
                        default: () => [
                            h(
                                NButton,
                                {
                                    type: 'primary',
                                    size: 'small',
                                    strong: true,
                                    secondary: true,
                                    disabled: false,  // 建造者全可以改
                                    onClick: async () => {
                                        dialog.warning({
                                            title: '警告',
                                            content: '启用任务么？',
                                            positiveText: '确定',
                                            negativeText: '不确定',
                                            onPositiveClick: () => {
                                                if (new Date(row.sendTime) < new Date()) {
                                                    message.warning('不可启用过去时间的定时任务')
                                                    return;
                                                }
                                                row.taskState = 'loading';
                                                startUserTask({ id: row.id, sendTime: new Date(row.sendTime) }).then(res => {
                                                    console.info(res)
                                                    if (res.status === 200) {
                                                        message.success(res.message);
                                                        init();
                                                    }
                                                })
                                            },
                                        })
                                    }
                                },
                                { default: () => '启用' }
                            ),
                            h(
                                NButton,
                                {
                                    type: 'error',
                                    size: 'small',
                                    strong: true,
                                    secondary: true,
                                    disabled: false,
                                    onClick: () => {
                                        dialog.error({
                                            title: '警告',
                                            content: '移除整个定时任务？',
                                            positiveText: '确定',
                                            negativeText: '不确定',
                                            onPositiveClick: () => {
                                                deleteTask({ id: row.id }).then(res => {
                                                    if (res.status === 200) {
                                                        // 如果发送中需先 删除定时器，后删除定时数据
                                                        message.success(res.message);
                                                        init();
                                                    }
                                                })
                                            },
                                        })

                                    }
                                },
                                { default: () => '移除' }
                            )

                        ]
                    }

                    )
                } else if (row.taskState === 'loading') {
                    return h(
                        NButton,
                        {
                            type: 'warning',
                            size: 'small',
                            strong: true,
                            secondary: true,
                            disabled: false,
                            onClick: () => {
                                if (row.taskState === 'off') {
                                    message.warning('任务未启动')
                                } else {
                                    row.taskState = 'on';
                                    removeUserTask({ id: row.id }).then(res => {
                                        if (res.status === 200) {
                                            message.success(res.message);
                                            init();
                                        }
                                    })
                                    return;
                                }
                            }
                        },
                        { default: () => '关闭' }
                    )
                } else if (row.taskState == 'on' || row.taskState === 'success') {
                    return h(
                        NButton,
                        {
                            type: 'error',
                            size: 'small',
                            strong: true,
                            secondary: true,
                            disabled: false,
                            onClick: () => {
                                dialog.error({
                                    title: '警告',
                                    content: '移除整个定时任务？',
                                    positiveText: '确定',
                                    negativeText: '不确定',
                                    onPositiveClick: () => {
                                        deleteTask({ id: row.id }).then(res => {
                                            if (res.status === 200) {
                                                // 如果发送中需先 删除定时器，后删除定时数据
                                                message.success(res.message);
                                                init();
                                            }
                                        })
                                    },
                                })

                            }
                        },
                        { default: () => '移除' }
                    )
                }
            }
        }
    ]
}
function checkCronTime(row: any): boolean {
    if (row.disabled) {
        return true;
    }
    if (currenName?.includes('Leon')) {
        return false;
    } else if (row.noteUsername === currenName) {
        return false;
    } else {
        return true;
    }

}


function closeDrawer() {
    cornTask.value = {};
}
let columns = createColumns()

function setRule() {
    if (!localStorage.getItem('u')) {
        columns = createColumns().filter((_item, index) => index < 2);
    } else if (localStorage.getItem('u') !== 'Leon') {
        columns = createColumns().filter((item, i) => {
            if (i == 2) {
                return;
            }
            return item;
        })
    }

}
// 禁用掉发送过的文章，避免二次创建
function checkSendTimeData() {
    resultTaskData.value.forEach(note => {
        resultData.value.forEach((item: any) => {
            if (item.id.includes(note.noteId)) {
                item.disabled = true;
            }
        })

    })
}

async function init() {
    setRule();
    noteDataLoading.value = true;
    await getNoteFormList({ search: '' }).then(res => {
        if (res.status === 200) {
            resultData.value = res.data;
            noteDataLoading.value = false;
            return;
        }
    }).catch(() => {
        noteDataLoading.value = false;
    })

    taskDataLoading.value = true;
    await taskList().then(res => {
        if (res.status === 200) {
            resultTaskData.value = res.data;
            resultTaskData.value.forEach(item => {
                item.key = item.noteId;
            })
            taskDataLoading.value = false;
            checkSendTimeData()
        }
    }).catch(() => {
        noteDataLoading.value = false;
    })


}
watch(() => cornTask.value.email, (newValue) => {
    const user = userOptions.value.find((item: any) => item.email === newValue)
    if (user) {
        cornTask.value.taskUserName = user.username
    }
})
onMounted(() => {
    init();
})


</script>

<style lang="scss">
.hotspot-container {

    padding: 20px;



}

.name {
    color: rgba(255, 0, 0, 0.75) !important;
}
</style>